<template>
  <div class="input_box">
    <el-autocomplete
      class="inline-input"
      v-model="value"
      :fetch-suggestions="querySearch"
      placeholder="请输入内容"
      @select="handleSelect"
      :clearable="clearable"
    >
      <div class="input_search_content" slot-scope="{ item }">
        <span style="color: #26B4FF">{{ item.keyValue }}</span
        ><span>{{ item.value }}</span>
      </div>
    </el-autocomplete>
  </div>
</template>

<script>
/*
封装的搜索高亮input框
*/
export default {
  props: {
    // 默认数据
    restaurants: {
      type: Array,
      default: []
    },
    // 是否显示清除icon
    clearable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      value: ""
    };
  },
  methods: {
    querySearch(queryString, cb) {
      // if (!cb) {
      //   this.restaurants = this.restaurants;
      //   return;
      // }
      var restaurants = this.restaurants;
      // 返回符合搜索条件的数组集合
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(queryString ? this.handleResults(results) : results);
      console.log(results);
    },
    // 处理返回结果
    handleResults(results) {
      return results.map((item, index) => {
        return {
          ...item,
          keyValue: item.value.substring(0, this.value.length),
          value: item.value.substring(this.value.length)
        };
      });
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return;
    },
    handleSelect(item) {
      this.$emit("handleSelect", item);
    }
  }
};
</script>

<style>
.input_search_content {
  overflow: inherit;
  text-overflow: ellipsis;
}
</style>
